package flc.ast.activity;

import android.graphics.Color;
import android.os.Handler;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.pdf.lib.model.IPdf2ImgListener;
import com.stark.pdf.lib.model.IPdfCreateListener;
import com.stark.pdf.lib.model.PdfUtil;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.PictureAdapter;
import flc.ast.adapter.PdfAdapter;
import flc.ast.bean.PdfBean;
import flc.ast.databinding.ActivityPictureFormatBinding;
import flc.ast.dialog.ConvertSucDialog;
import flc.ast.dialog.CreateDialog;
import flc.ast.dialog.FormatDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class PictureFormatActivity extends BaseAc<ActivityPictureFormatBinding> {

    private PictureAdapter pictureAdapter;
    private PdfAdapter pdfAdapter;
    private List<String> listSel = new ArrayList<>();
    private String newName = "";
    private String selPath = "";
    private int oldPosition;
    private int type;

    @Override
    protected int onCreate() {
        return R.layout.activity_picture_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPictureFormatBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivConvertPdf.setOnClickListener(this);
        mDataBinding.ivConvertPic.setOnClickListener(this);
        mDataBinding.ivPictureFormatSave.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        pictureAdapter = new PictureAdapter();
        mDataBinding.rvFileList.setAdapter(pictureAdapter);
        pictureAdapter.setOnItemClickListener(this);

        pdfAdapter = new PdfAdapter();
        pdfAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivConvertPdf://转pdf
                clearSelection();
                type = 0;
                mDataBinding.ivConvertPdf.setImageResource(R.drawable.kj_pdf);
                getPicData();
                mDataBinding.rvFileList.setAdapter(pictureAdapter);
                break;
            case R.id.ivConvertPic://转图片
                clearSelection();
                type = 1;
                mDataBinding.ivConvertPic.setImageResource(R.drawable.kj_tp2);
                getPdfData();
                mDataBinding.rvFileList.setAdapter(pdfAdapter);
                break;
            case R.id.ivPictureFormatSave://保存
                if (type == 0) {
                    showResolutionDialog();
                } else {
                    pdfConvImg();
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == pictureAdapter) {
            if (pictureAdapter.getItem(position).isChecked()) {
                pictureAdapter.getItem(position).setChecked(false);
                listSel.remove(pictureAdapter.getItem(position).getPath());
            } else {
                pictureAdapter.getItem(position).setChecked(true);
                listSel.add(pictureAdapter.getItem(position).getPath());
            }
            pictureAdapter.notifyItemChanged(position);
        } else if (adapter == pdfAdapter) {
            pdfAdapter.getItem(oldPosition).setSelected(false);
            oldPosition = position;
            pdfAdapter.getItem(position).setSelected(true);
            pdfAdapter.notifyDataSetChanged();
            selPath = pdfAdapter.getItem(position).getPath();
        }
    }

    @Override
    protected void initData() {
        getPicData();
    }

    //获取视频和图片数据
    private void getPicData() {
        showDialog(getString(R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    pictureAdapter.setList(selectMediaEntities);
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.tvFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
                }
                dismissDialog();
            }
        });
    }

    //获取文档数据
    private void getPdfData() {
        List<PdfBean> listShow = new ArrayList<>();
        //设置获取的数据类型 只获取pdf
        List<String> type = new ArrayList<>();
        type.add("application/pdf");
        RxUtil.create(new RxUtil.Callback<List<MediaInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MediaInfo>> emitter) {
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                emitter.onNext(infoList);
            }

            @Override
            public void accept(List<MediaInfo> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    for (MediaInfo bean : selectMediaEntities) {
                        listShow.add(new PdfBean(bean.getPath()));
                    }
                }
                if (listShow.size() > 0) {
                    pdfAdapter.setList(listShow);
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.tvFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //图片转PDF
    private void imgConvPdf() {
        PdfUtil.img2Pdf(listSel, newName, new IPdfCreateListener() {
            @Override
            public void onStart() {
                showDialog(getString(R.string.conv_ing));
            }

            @Override
            public void onEnd(boolean success, String path) {
                dismissDialog();
                if (success) {
                    String suffix = FileUtils.getFileExtension(path);
                    String desPath = PathUtils.getFilesPathExternalFirst() + FileUtils.getFileNameNoExtension(path) + "." + suffix;
                    FileUtils.copy(path, desPath);
//                    String filePath = FileUtil.generateFilePath(Content.myRecentFile, "." + FileUtils.getFileExtension(path));
//                    FileUtils.copy(path, filePath);
                    showPdfSucDialog();
                } else {
                    ToastUtils.showShort(getString(R.string.conv_def));
                }
            }
        });
    }

    //PDF转图片
    private void pdfConvImg() {
        PdfUtil.pdf2Img(selPath, new IPdf2ImgListener() {
            @Override
            public void onStart() {
                showDialog(getString(R.string.conv_ing));
            }

            @Override
            public void onEnd(int imageCount, List<String> outputFilePaths) {
                dismissDialog();
                if (outputFilePaths == null || outputFilePaths.size() == 0) {
                    ToastUtils.showShort(R.string.conv_def);
                } else {
                    String path = outputFilePaths.get(0);
                    //保存到相册
                    FileP2pUtil.copyPrivateImgToPublic(mContext, path);
                    String filePath = FileUtil.generateFilePath(Content.myRecentFile, "." + FileUtils.getFileExtension(path));
                    FileUtils.copy(path, filePath);
                    showPicSucDialog();
                }
            }
        });
    }

    private void showResolutionDialog() {
        CreateDialog createDialog = new CreateDialog(mContext);
        createDialog.setListener(new CreateDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                newName = name;
                imgConvPdf();
            }
        });
        createDialog.show();
    }

    private void showPdfSucDialog() {
        ConvertSucDialog convertSucDialog = new ConvertSucDialog(mContext);
        convertSucDialog.content = getString(R.string.save_to_file);
        convertSucDialog.show();
    }

    private void showPicSucDialog() {
        ConvertSucDialog convertSucDialog = new ConvertSucDialog(mContext);
        convertSucDialog.show();
    }

    private void clearSelection() {
        mDataBinding.ivConvertPdf.setImageResource(R.drawable.kj_pdf2);
        mDataBinding.ivConvertPic.setImageResource(R.drawable.kj_tp);
    }

}